<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="仓库">
              <a-auto-complete v-model:value="productStorageWhere.warehousename_val" :options="warehousenameOptions"
                placeholder="请输入仓库" @select="warehousename_onSelect2" @search="warehousename_onSearch" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="产品">
              <a-auto-complete v-model:value="productStorageWhere.productname_val" :options="productnameOptions"
                placeholder="请输入产品" @select="productname_onSelect2" @search="productname_onSearch"
                @blur="productname_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="规格">
              <a-input v-model:value.trim="productStorageWhere.specification" placeholder="规格" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="productStorageReload">查询</a-button>
                <a-button @click="productStorageReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="productStorageTableRef" row-key="id" :columns="columns" :datasource="datasource"
        :scroll="{ x: 1000 }" cacheKey="productStorage">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="productStorageOpenEdit()" v-any-permission="['store:productStorage:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>
        <template #summary>
          <a-table-summary-row>
            <a-table-summary-cell :col-span="2">总重量</a-table-summary-cell>
            <a-table-summary-cell :col-span="2">
              <a-typography-text type="danger">
                {{ liTotalWeightTotal }}
              </a-typography-text>
            </a-table-summary-cell>
          </a-table-summary-row>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="productStorageOpenEdit(record)" v-any-permission="['store:productStorage:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="productStorageRemove(record)">
                <a class="ele-text-danger" v-any-permission="['store:productStorage:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 库存添加、修改弹窗 -->
    <ele-modal :width="660" v-model:visible="productStorageVisible_modal" :confirm-loading="loading"
      :title="productStorageIsUpdate ? '修改库存' : '添加库存'" position="center" :body-style="{ paddingBottom: '8px' }"
      @ok="productStorageSave" :maskClosable="false">
      <a-form ref="productStorageFormRef" :model="productStorageForm" :rules="productStorageRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="仓库" name="warehousename_val">
              <a-auto-complete v-model:value="productStorageForm.warehousename_val" :options="warehousenameOptions"
                placeholder="请输入仓库" @select="warehousename_onSelect" @search="warehousename_onSearch"
                @blur="warehousename_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="产品" name="productname">
              <a-input allow-clear :maxlength="200" placeholder="请输入产品" v-model:value="productStorageForm.productname"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="规格" name="specification">
              <a-input allow-clear :maxlength="200" placeholder="请输入规格" v-model:value="productStorageForm.specification"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="长度" name="lengths">
              <a-input allow-clear :maxlength="200" placeholder="请输入长度" v-model:value="productStorageForm.lengths"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="负差" name="negative">
              <a-input allow-clear :maxlength="200" placeholder="请输入负差" v-model:value="productStorageForm.negative"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="数量" name="num">
              <a-input allow-clear :maxlength="200" placeholder="请输入数量" v-model:value="productStorageForm.num"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="理论质量" name="liweight">
              <a-input allow-clear :maxlength="200" placeholder="请输入理论质量" v-model:value="productStorageForm.liweight"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="总重量" name="litotalweight">
              <a-input allow-clear :maxlength="200" placeholder="请输入总重量"
                v-model:value="productStorageForm.litotalweight" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="价格" name="price">
              <a-input allow-clear :maxlength="200" placeholder="请输入价格" v-model:value="productStorageForm.price"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="材质" name="model">
              <a-input allow-clear :maxlength="200" placeholder="请输入材质" v-model:value="productStorageForm.model"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="产地" name="locality">
              <a-input allow-clear :maxlength="200" placeholder="请输入产地" v-model:value="productStorageForm.locality"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="排序" name="ordernum">
              <a-input allow-clear :maxlength="200" placeholder="请输入排序" v-model:value="productStorageForm.ordernum"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="备注" name="remark">
              <a-textarea :rows="4" :maxlength="200" placeholder="请输入备注" v-model:value="productStorageForm.remark"
                autocomplete="off" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import { pageProductStorage, removeProductStorage, addProductStorage, updateProductStorage } from '@/api/store/productStorage';
import { listWarehouseSel } from '@/api/store/warehouse'
import { listProductSelUnique } from '@/api/store/product'

// 表格实例
const productStorageTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (productStorageTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '仓库',
    dataIndex: 'warehousename',
    key: 'warehousename',
    sorter: true
  },
  {
    title: '产品',
    dataIndex: 'productname',
    key: 'productname',
    sorter: true
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    sorter: true
  },
  {
    title: '长度',
    dataIndex: 'lengths',
    key: 'lengths',
    sorter: true
  },
  {
    title: '负差',
    dataIndex: 'negative',
    key: 'negative',
    sorter: true
  },
  {
    title: '数量',
    dataIndex: 'num',
    key: 'num',
    sorter: true
  },
  {
    title: '理论质量',
    dataIndex: 'liweight',
    key: 'liweight',
    sorter: true
  },
  {
    title: '总重量',
    dataIndex: 'litotalweight',
    key: 'litotalweight',
    sorter: true
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    sorter: true,
    hideInSetting: false,//右上角的小方块 true为隐藏
    hideInTable: true,//表格的行里 true为隐藏
  },
  {
    title: '材质',
    dataIndex: 'model',
    key: 'model',
    sorter: true,
    hideInSetting: false,//右上角的小方块 true为隐藏
    hideInTable: true,//表格的行里 true为隐藏
  },
  {
    title: '产地',
    dataIndex: 'locality',
    key: 'locality',
    sorter: true,
    hideInSetting: false,//右上角的小方块 true为隐藏
    hideInTable: true,//表格的行里 true为隐藏
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    sorter: true,
    hideInSetting: false,//右上角的小方块 true为隐藏
    hideInTable: true,//表格的行里 true为隐藏
  },
  // {
  //   title: '创建时间',
  //   dataIndex: 'createTime',
  //   key: 'createTime',
  //   resizable: true,
  //   width: 150,
  //   ellipsis: true,
  //   customRender: ({ text }) => toDateString(text)
  // },
  // {
  //   title: '创建人',
  //   dataIndex: 'createName',
  //   key: 'createName',
  // },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    sorter: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: false,//右上角的小方块 true为隐藏
    hideInTable: true,//表格的行里 true为隐藏
  }
]);

// 表单数据
const { form: productStorageWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});
let liTotalWeightTotal = ref(0)
// 表格数据源
const datasource = async ({ page, limit, where, orders }) => {
  let data_temp = {}
  orders.sort = orders.sort == 'updateTime' ? 'update_time' : orders.sort
  orders.sort = orders.sort == 'createTime' ? 'create_time' : orders.sort
  await pageProductStorage({ ...where, ...orders, page, limit }).then(data => {
    data_temp = data.data.data
    liTotalWeightTotal.value = data.liTotalWeightTotal
  })
  return new Promise((resolve) => {
    resolve(data_temp)
  })
};

/* 搜索 */
const productStorageReload = () => {
  productStorageTableRef?.value?.reload({ page: 1, where: productStorageWhere });
};
const productStorageReload2 = () => {
  productStorageTableRef?.value?.reload();
};

let productStorageWhere_timeout = 0
watch(() => productStorageWhere, (val) => {
  clearTimeout(productStorageWhere_timeout)
  productStorageWhere_timeout = setTimeout(() => {
    productStorageReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const productStorageReset = () => {
  resetFields();
  productStorageReload();
};

/* 删除单个 */
const productStorageRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeProductStorage(record.id).then((msg) => {
    hide();
    message.success(msg);
    productStorageReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const productStorageCurrent = ref(null);

// 弹窗是否打开
const productStorageVisible_modal = ref(false);

// 是否是修改
const productStorageIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const productStorageFormRef = ref(null);

// 表单数据
const { form: productStorageForm, resetFields: productStorageResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  warehousename_val: '',
});

// 表单验证规则
const productStorageRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});



//防止重复刷新
//仓库名称下拉列表
let warehousename_m_timeout = 0
const warehousenameOptions = ref([]);
const warehousename_onSearch = searchText => {
  clearTimeout(warehousename_m_timeout)
  warehousename_m_timeout = setTimeout(() => {
    listWarehouseSel({ 'warehousename': searchText }).then(msg => {
      warehousenameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
warehousename_onSearch('')
const warehousename_onSelect = (value2, option2) => {
  // let a = warehousenameOptions.value.find((item)=> {return item.value=value})
  productStorageForm.warehousename_val = option2.label
  productStorageForm.warehousename = option2.label
  productStorageForm.warehousenameId = option2.value
};

const warehousename_blur = () => {
  productStorageForm.warehousename_val = productStorageForm.warehousename
};
//where 搜索
const warehousename_onSelect2 = (value2, option2) => {
  // let a = warehousenameOptions.value.find((item)=> {return item.value=value})
  productStorageWhere.warehousename_val = option2.label
  productStorageWhere.warehousename = option2.label
  productStorageWhere.warehousenameId = option2.value
};
watch(() => productStorageWhere.warehousename_val, (val) => {
  productStorageWhere.warehousename = val
},
)

//产品名称下拉列表
let productname_m_timeout = 0
const productnameOptions = ref([]);
const productname_onSearch = searchText => {
  clearTimeout(productname_m_timeout)
  productname_m_timeout = setTimeout(() => {
    listProductSelUnique({ name: searchText }).then(msg => {
      productnameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
productname_onSearch('')
const productname_onSelect2 = (value2, option2) => {
  // let a = productnameOptions.value.find((item)=> {return item.value=value})
  productStorageWhere.productname_val = option2.name
  productStorageWhere.productname = option2.name
  // productStorageWhere.productnameId = option2.value
  // productStorageWhere.specification = option2.specification
  // productStorageWhere.liweight = option2.liWeight
  // productStorageWhere.lengths = option2.lengths
  // productStorageWhere.negative = option2.negative
  // productStorageWhere.code = option2.code
};
watch(() => productStorageWhere.productname_val, (val) => {
  productStorageWhere.productname = val
},
)

/* 打开编辑弹窗 */
const productStorageOpenEdit = (record) => {
  productStorageResetFormFields();
  productStorageFormRef.value?.clearValidate();
  productStorageCurrent.value = record ?? {};
  productStorageVisible_modal.value = true;
  Object.assign(productStorageForm, record ?? {});
  productStorageIsUpdate.value = !!record;
  productStorageForm.warehousename_val = productStorageForm.warehousename
};

/* 保存编辑 */
const productStorageSave = () => {
  if (!productStorageFormRef.value) {
    return;
  }
  productStorageFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = productStorageIsUpdate.value ? updateProductStorage : addProductStorage;
    saveOrUpdate(productStorageForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      productStorageVisible_modal.value = false;
      productStorageReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<script>
export default {
  name: 'ProductStorage'
};
</script>
